package com.sky.controller.admin;

import com.sky.dto.SetmealDTO;
import com.sky.dto.SetmealPageQueryDTO;
import com.sky.result.PageResult;
import com.sky.result.Result;
import com.sky.service.SetmealService;
import com.sky.vo.SetmealVO;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.ibatis.annotations.Delete;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Set;

@RequestMapping("/admin/setmeal")
@RestController
@Slf4j
@Api("套餐相管接口")
public class SetmealController {
    @Autowired
    private SetmealService setmealService;
    @Autowired
    private RedisTemplate redisTemplate;

    /**
     * 分页查询
     * @param setmealPageQueryDTO
     * @return
     */
    @GetMapping("/page")
    @ApiOperation("分页查询")
    public Result<PageResult> page(SetmealPageQueryDTO setmealPageQueryDTO){
        PageResult pageResult= setmealService.page(setmealPageQueryDTO);
        return Result.success(pageResult);
    }

    /**
     * 新增套餐
     * @param setmealDTO
     * @return
     */
    @PostMapping
    @ApiOperation("新增套餐")
    @CacheEvict(cacheNames = "categoryCache",key = "#setmealDTO.categoryId")
    public Result save(@RequestBody SetmealDTO setmealDTO){
        String key = "setmeal_"+setmealDTO.getCategoryId();
        setmealService.save(setmealDTO);
        return Result.success();
    }

    /**
     * 根据Id查询套餐
     * @param id
     * @return
     */
    @ApiOperation("根据Id查询套餐")
    @GetMapping("/{id}")
    public Result<SetmealVO> queryById(@PathVariable Long id){
        SetmealVO setmealVO= setmealService.queryById(id);
        return Result.success(setmealVO);
    }

    /**
     * 修改套餐
     * @return
     */
    @PutMapping
    @ApiOperation("修改套餐")
    @CacheEvict(cacheNames = "categoryCache",allEntries = true)
    public Result updateById(@RequestBody SetmealDTO setmealDTO){
        //清楚redsi中所有以setmeal开头的数据
        setmealService.updateById(setmealDTO);
        return Result.success();
    }
    @DeleteMapping
    @ApiOperation("删除套餐")
    @CacheEvict(cacheNames = "categoryCache",allEntries = true)
    public Result deleteById(@RequestParam List<Long> ids){
        setmealService.delete(ids);
        return Result.success();
    }
    @PostMapping("/status/{status}")
    @CacheEvict(cacheNames = "categoryCache",allEntries = true)
    public Result changeStatus(@PathVariable Integer status,Long id){

        setmealService.chageStatus(status,id);
        return Result.success();
    }
/*    private void cleanCache(String pattern) {
        Set keys = redisTemplate.keys(pattern);
        redisTemplate.delete(keys);
    }*/
}
